import { computed, ref } from 'vue'
import { FieldInterface, TableInterface } from '../TableType'
// import { tableList as tl } from '../testData'
import { useModuleStore } from '@/store/moduleStore'
const moduleStore = useModuleStore()
let tl = computed(() => moduleStore.currentModuleTable)

export default function (tableSelected: any) {
  // 字段选择
  const fieldSelected = ref([] as any[])
  const fieldList = computed(() => {
    let fields = tl.value.filter(item => {
      if (tableSelected.value.includes(item.value as never)) {
        return true
      }
    })
    return fields
  })

  /**
   * 选择字段全选复选框
   *
   * @param isSelected 是否选中
   * @param index 索引
   */
  function fieldSelectAllCheckBox (isSelected: any, index: number) {
    if (isSelected) {
      fieldSelected.value[index].fields = fieldList.value
        .filter(i => i.value == fieldSelected.value[index].table)[0]
        .fields.map((i: any) => i.value)
      fieldSelectChange(
        fieldSelected.value[index].fields,
        index,
        fieldList.value[index].fields
      )
    } else {
      fieldSelected.value[index].fields = []
    }
  }
  /**
   * 当字段选择发生变化时触发的函数
   *
   * @param e 选择变化后的值，是一个数组
   * @param index 当前操作字段的索引
   */
  function fieldSelectChange (e: any, index: number, fieldList: Array<any>) {
    //检查是否存在此别名，不存在添加，多余删除
    let arr = fieldSelected.value[index].fieldAliasNameMapArray
      ? fieldSelected.value[index].fieldAliasNameMapArray
      : []
    //不存在的添加
    for (let i = 0; i < e.length; i++) {
      let isExist = false
      for (let j = 0; j < arr.length; j++) {
        if (arr[j].name == e[i]) {
          isExist = true
        }
      }
      if (!isExist) {
        arr.push({ name: e[i], aliasName: '' })
      }
      // 匹配别名
      for (let j = 0; j < arr.length; j++) {
        fieldList.forEach((item: FieldInterface) => {
          if (item.value == arr[j].name) {
            arr[j].aliasName = item.aliasName
          }
        })
      }
    }
    //多余的删除
    let noExist = []
    for (let j = 0; j < arr.length; j++) {
      if (!e.includes(arr[j].name)) {
        noExist.push(arr[j].name)
      }
    }
    fieldSelected.value[index].fieldAliasNameMapArray = arr.filter(
      (item: any) => !noExist.includes(item.name)
    )

    fieldSelected.value[index].isSelectAllField = e.length == fieldList.length
  }
  return {
    fieldSelected,
    fieldSelectAllCheckBox,
    fieldSelectChange,
    fieldList
  }
}
